import winsound,time
from from_WebSite1 import GetWebSite1
from from_WebSite2 import GetWebSite2
from my_error import NewResultError
from tkinter import messagebox

# 當出現新搜索結果時 蜂鳴 彈窗警告 發送郵件
def warning():
    winsound.Beep(8000,5000) # 主板蜂鸣器 winsound.Beep(frequency, duration) 表示以蜂鸣器 f Hz 响时 d ms。
    messagebox.showerror("檢查","檢查")
    # email

# 打印當前時間並暫停數分鐘
def waiting(minute:int):
    localtime_0 = time.localtime()
    print("Current time: ", time.strftime("%Y-%m-%d %H:%M:%S",localtime_0))
    print("Waiting...")
    time.sleep(60*minute)

# 搜索 WebSite1 WebSite2
def main(WebSite1_data:dict={}, WebSite2_data:dict={}, turn:int = 0):
    temp = 1
    ws1_downloader = GetWebSite1(WebSite1_data)
    ws2_downloader = GetWebSite2(WebSite2_data)
    while temp<=turn or turn<=0:
        print("Start the "+ str(temp) + "th search")
        try:
            new_ws1_data = ws1_downloader.get_result()
            if new_ws1_data == WebSite1_data:
                pass
            else:
                for key in new_ws1_data:
                    if new_ws1_data[key] != WebSite1_data[key] and new_ws1_data[key] != -1:
                        print("New search result: WebSite1", key, new_ws1_data[key])
                        raise NewResultError("WebSite1")
                    elif new_ws1_data[key] != WebSite1_data[key] and new_ws1_data[key] == -1:
                        print("WebSite1: Maybe net error: ", key)

            new_wb2_data = ws2_downloader.get_result()
            if new_wb2_data == WebSite2_data:
                pass
            else:
                for key in new_wb2_data:
                    if new_wb2_data[key] != WebSite2_data[key] and new_wb2_data[key] != -1:
                        print("New search result: WebSite2", key, new_wb2_data)
                        raise NewResultError("WebSite2")
                    elif new_wb2_data[key] != WebSite2_data[key] and new_wb2_data[key] == -1:
                        print("WebSite2: Maybe net error: ", key, new_wb2_data[key])
        except NewResultError as e:
            # warning()
            from os import system
            system("pause")
            break
        except KeyboardInterrupt as e:
            print("Keyboard stop when searching.")
            break
        else:
            print("WebSite1: Safe")
            print("WebSite2: Safe")
            print("The " + str(temp) + "th search ended.")
            if temp==turn:
                break
            temp += 1
            try:
                waiting(5)
            except KeyboardInterrupt as e:
                print("Keyboard stop when waiting.")
                break
    print("All searches have ended, {} times in total".format(temp-1))

if __name__ == "__main__":
    WebSite1_data = {'kw1':0, 'kw2':0} # 2023-9-5 09:46:45
    WebSite2_data = {'kw1':0, 'kw2':0} # 2023-9-3 16:37:56
    main(WebSite1_data, WebSite2_data)